import router, { anyroutes, asyncroutes } from '@/router'
import { cloneDeep } from 'lodash-es'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { type ChangePasswordReq, type CheckUser, type LoginReq, type UpdateUserInfo } from './type'
import { reqChangePassword, reqLogin, reqUpdateUserInfo, reqUserInfo } from './user.api'

const filterAsyncRoute = (asyncroutes: RouteRecordRaw[], routes: string[]): RouteRecordRaw[] => {
  return asyncroutes.filter((item) => {
    if (item.name && routes.includes(item.name as string)) {
      // 当前路由在权限中，保留并递归处理子路由
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }

    // 当前路由不在权限中，但有子路由，检查子路由是否有匹配的
    if (item.children && item.children.length > 0) {
      item.children = filterAsyncRoute(item.children, routes)
      // 如果有子路由被保留，则保留当前路由（作为容器）
      return item.children.length > 0
    }

    // 当前路由和子路由都不在权限中，过滤掉
    return false
  })
}

const useUserStore = defineStore(
  'user',
  () => {
    // 用户认证令牌，初始值为空字符串，实际值会从 localStorage 中自动恢复
    const token = ref<string>('')
    const userInfo = ref<CheckUser>()
    const userAllRoutes = ref<RouteRecordRaw[]>([])

    //  用户登录函数
    const login = async (req: LoginReq) => {
      const { data } = await reqLogin(req)
      token.value = data.data as string
    }

    // 获取用户信息
    const userInfoReq = async () => {
      try {
        const { data } = await reqUserInfo()
        userInfo.value = data.data as CheckUser

        //计算当前用户需要展示的异步路由
        const userAsyncRoute = filterAsyncRoute(cloneDeep(asyncroutes), userInfo.value.routes)
        userAllRoutes.value = [...userAsyncRoute, ...anyroutes]

        // 动态追加路由
        userAllRoutes.value.forEach((route) => {
          router.addRoute(route)
        })
      } catch {
        console.log('获取用户信息失败，退出登录')
        await logout()
      }
    }

    // 修改用户密码
    const changePassword = async (req: ChangePasswordReq) => {
      await reqChangePassword(req)
    }

    // 修改用户资料
    const updateUserInfo = async (data: UpdateUserInfo) => {
      return await reqUpdateUserInfo(data)
    }

    // 退出登录
    const logout = () => {
      token.value = ''
      userInfo.value = undefined
      userAllRoutes.value = []
      // 立即跳转到登录页，确保用户无法继续访问受保护的页面
      router.push('/login')
    }

    return {
      token,
      userInfo,
      userAllRoutes,
      login,
      userInfoReq,
      logout,
      changePassword,
      updateUserInfo,
    }
  },
  {
    persist: {
      key: 'user', // 存储的key名（默认同store id）
      storage: localStorage, // 存储方式
      // 只持久化 token 和 userInfo，不持久化 userAllRoutes
      pick: ['token', 'userInfo'],
    },
  },
)

//菜单权限管理

export default useUserStore
